import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/dialog/focus_tencent_diaog.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/home/model/common_item_model.dart';
import 'package:tender_flutter/page/home/model/user_info_entity.dart';
import 'package:tender_flutter/page/person/api/api_person.dart';
import 'package:tender_flutter/page/person/model/member_combo_entity.dart';
import 'package:tender_flutter/providers/provider.dart';
import 'package:tender_flutter/providers/user_profile.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/widgets/animation_dialog.dart';
import 'package:tender_flutter/widgets/net_image.dart';
import 'package:tender_flutter/widgets/part_refresh_widget.dart';

import 'model/pay_params.dart';

class MemberCentrePage extends StatefulWidget {
  @override
  _MemberCentrePageState createState() => _MemberCentrePageState();
}

class _MemberCentrePageState extends State<MemberCentrePage> {
  /// 选中的会员套餐
  int selectComboIndex = 0;

  /// 套餐数据
  List<MemberComboEntity> _comboDatas;

  /// 权限信息
  List<CommonItemModel> _permissionDatas;

  Future _future;

  /// 是否是第一次点击返回
  bool isFirstBack = true;

  double _titleAlpha = 1;

  double expandedHeight = ScreenAdapter.height(250);

  GlobalKey<PartRefreshWidgetState> _titleKey = GlobalKey();

  ScrollController _scrollController = ScrollController();

  /// 获取用户信息
  Future _getUserInfo() async {
    var response = await ApiPerson.getUserInfo<UserInfoEntity>();
    Store.value<UserProfileInfo>(context).setUserInfo(response.result);
  }

  /// 获取套餐
  Future<ApiResponse<List<MemberComboEntity>>> _getComboData() async {
    return await ApiPerson.getMemberCombo<List<MemberComboEntity>>();
  }

  FutureBuilder<ApiResponse<List<MemberComboEntity>>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _future,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<List<MemberComboEntity>>> snapshot) {
          if (snapshot.hasData) {
            List temps = snapshot.data.result;

            /// 默认选中,第一次请求数据完成的时候设置默认选中
            if (_comboDatas == null) {
              for (MemberComboEntity entity in temps) {
                print(entity.isDefault);
                if (entity.isDefault == true) {
                  selectComboIndex = temps.indexOf(entity);
                }
              }
            }

            _comboDatas = temps;

            return _initSetMealList();
          } else {
            return SliverPadding(
              padding: EdgeInsets.all(30),
            );
          }
        });
  }

  /// 页面返回时弹出关注公众号弹窗
  _showFocusTencentDialog() {
    showAnimationDialog(
        context: context,
        transitionType: TransitionType.fade,
        builder: (context) {
          return FocusTencentDiaog();
        });
  }

  /// pop操作
  _navback() {
    // if (!isFirstBack) {
    //   LRouter.navigatorCtx(context).pop();
    // } else {
    //   _showFocusTencentDialog();
    //   isFirstBack = false;
    // }
    LRouter.navigatorCtx(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          backgroundColor: ThemeColors.colorWhite,
          body: _initBody(),
        ),
        onWillPop: () {
          _navback();
          return Future.value(false);
        });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _future = _getComboData();
    _permissionDatas = [
      CommonItemModel(title: "招标查询", image: "icon_p_1.png"),
      CommonItemModel(title: "中标查询", image: "icon_p_2.png"),
      CommonItemModel(title: "企业查询", image: "icon_p_3.png"),
      // CommonItemModel(title: "资质查询", image: "icon_p_4.png"),
      CommonItemModel(title: "需求发布", image: "icon_p_5.png"),
      CommonItemModel(title: "供应发布", image: "icon_p_6.png"),
      // CommonItemModel(title: "VIP项目", image: "icon_p_7.png"),
      CommonItemModel(title: "PPP项目", image: "icon_p_8.png"),
      CommonItemModel(title: "订阅推送", image: "icon_p_9.png"),
      CommonItemModel(title: "优质供应商", image: "icon_p_10.png"),
      CommonItemModel(title: "企业追踪", image: "icon_p_11.png"),
      CommonItemModel(title: "军队采购", image: "icon_p_12.png"),
      CommonItemModel(title: "铁路采购", image: "icon_p_13.png"),
      CommonItemModel(title: "信息收藏", image: "icon_p_14.png"),
      // CommonItemModel(title: "数据导出", image: "icon_p_15.png")
    ];

    _scrollController
      ..addListener(() {
        print(_scrollController.offset);
        if (_scrollController.offset <= 0) {
          _titleAlpha = 1;
        } else if (_scrollController.offset <= kToolbarHeight) {
          _titleAlpha = 1 - _scrollController.offset / kToolbarHeight;
        } else {
          _titleAlpha = 0;
        }
        _titleKey.currentState.update();
      });

    /// 页面渲染完成之后的回调，只执行一次
    WidgetsBinding.instance.addPostFrameCallback((mag) {
      _getUserInfo();
    });
  }

  /// 内容
  Widget _initBody() {
    return Stack(children: [
      CustomScrollView(
        physics: const BouncingScrollPhysics(),
        controller: _scrollController,
        slivers: <Widget>[
          new SliverAppBar(
              centerTitle: true,
              title: PartRefreshWidget(_titleKey, () {
                return Opacity(
                    opacity: _titleAlpha,
                    child: Text("会员中心",
                        style: FonStyle.navTextStyle(
                            textColor: ThemeColors.colorWhite)));
              }),
              pinned: true,
              floating: false,
              primary: true,
              // collapsedHeight: ScreenAdapter.height(20),
              expandedHeight: expandedHeight,
              toolbarHeight: kToolbarHeight + ScreenAdapter.height(40),
              elevation: 0,
              //是否显示阴影，直接取值innerBoxIsScrolled，展开不显示阴影，合并后会显示
              forceElevated: false,
              leading: new IconButton(
                icon: Icon(Icons.arrow_back_ios),
                onPressed: () {
                  _navback();
                },
              ),
              actions: <Widget>[
                FlatButton(
                    onPressed: () {
                      LRouter.navigatorCtx(context)
                          .push(Routes.consumptionPage);
                    },
                    child: Text(
                      "购买记录",
                      style: TextStyle(
                          fontSize: ScreenAdapter.sp(30),
                          color: ThemeColors.colorWhite),
                    ))
              ],
              flexibleSpace: new FlexibleSpaceBar(
                background: Container(
                  color: ThemeColors.colorWhite,
                  child: Image.asset(
                      RPath.imgPath + "img_member_center_top_bg.png",
                      fit: BoxFit.fill),
                ),
                centerTitle: true,
                title: _initUserInfoView(),
                titlePadding: EdgeInsets.zero,
                stretchModes: [StretchMode.fadeTitle],
                collapseMode: CollapseMode.parallax,
              )),
          _initTitleView("开通VIP会员"),
          SliverPadding(
            padding: EdgeInsets.all(ScreenAdapter.width(30)),
            sliver: _buildFutureBuilder(),
          ),
          _initTitleView("会员权益"),
          SliverPadding(
            padding: EdgeInsets.all(ScreenAdapter.width(30)),
            sliver: _initpermissionsList(),
          ),
          SliverPadding(
              padding: EdgeInsets.only(bottom: ScreenAdapter.height(120)))
        ],
      ),
      _initSubmitBtn()
    ]);
  }

  /// 用户信息
  Widget _initUserInfoView() {
    return Consumer(
        builder: (BuildContext ctx, UserProfileInfo profileInfo, Widget child) {
      return Container(
        height: kToolbarHeight,
        alignment: Alignment.centerLeft,
        margin: EdgeInsets.only(
            left: ScreenAdapter.width(60), bottom: ScreenAdapter.height(20)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
                width: kToolbarHeight / 1.5,
                height: kToolbarHeight / 1.5,
                decoration: BoxDecoration(
                  border: new Border.all(
                    color: ThemeColors.colorWhite, //边框颜色
                    width: 1, //边框宽度
                  ),
                  borderRadius: BorderRadius.circular(ScreenAdapter.width(40)),
                ),
                child: GestureDetector(
                    onTap: () {},
                    child: MyNetImage(
                        url: profileInfo.userInfo.picture ?? "",
                        radius:
                            BorderRadius.circular((kToolbarHeight / 1.5) / 2),
                        placeholder: Image.asset(
                            RPath.imgPath + "img_portait_placeholder.png")))),
            SizedBox(width: ScreenAdapter.width(10)),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                // SizedBox(height: ScreenAdapter.height(5)),
                Text(profileInfo.userInfo.phone ?? "-",
                    style: TextStyle(
                      fontSize: ScreenAdapter.sp(22),
                      color: ThemeColors.colorWhite,
                    )),
                SizedBox(
                  height: ScreenAdapter.height(10),
                ),
                Text(
                  _getMyVipDes(entity: profileInfo.userInfo),
                  style: TextStyle(
                    fontSize: ScreenAdapter.sp(17),
                    color: ThemeColors.colorType29,
                  ),
                ),
                // SizedBox(height: ScreenAdapter.height(5)),
              ],
            ),
          ],
        ),
      );
    });
  }

  /// 标题
  Widget _initTitleView(String title) {
    return SliverPadding(
      padding: EdgeInsets.symmetric(
          horizontal: ScreenAdapter.width(30),
          vertical: ScreenAdapter.height(15)),
      sliver: SliverToBoxAdapter(
        child: Text(
          title,
          style: TextStyle(
              color: ThemeColors.colorType1,
              fontSize: ScreenAdapter.sp(32),
              fontWeight: FontWeight.bold),
        ),
      ),
    );
  }

  /// 会员套餐
  Widget _initSetMealList() {
    return SliverGrid(
        delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
          return _getSetMealCell(index);
        }, childCount: _comboDatas.length),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: ScreenAdapter.width(30),
            mainAxisSpacing: ScreenAdapter.height(40),
            childAspectRatio: 1.3));
  }

  /// 会员权益
  Widget _initpermissionsList() {
    return SliverGrid(
        delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
          return _getPermissionCell(_permissionDatas[index]);
        }, childCount: _permissionDatas.length),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4,
            crossAxisSpacing: ScreenAdapter.width(20),
            mainAxisSpacing: ScreenAdapter.height(20),
            childAspectRatio: 1));
  }

  /// 提交按钮
  Widget _initSubmitBtn() {
    return Consumer(
        builder: (BuildContext ctx, UserProfileInfo profileInfo, Widget child) {
      return Positioned(
          left: ScreenAdapter.width(30),
          right: ScreenAdapter.width(30),
          bottom: ScreenAdapter.width(30),
          child: Container(
              // margin: EdgeInsets.symmetric(
              //     horizontal: ScreenAdapter.width(30),
              //     vertical: ScreenAdapter.height(30)),
              decoration: BoxDecoration(
                  color: ThemeColors.colorType30,
                  borderRadius: BorderRadius.circular(ScreenAdapter.width(14))),
              child: FlatButton(
                  onPressed: () {
                    MemberComboEntity entity = _comboDatas[selectComboIndex];
                    PayParams params = PayParams();
                    String des = profileInfo.userInfo.isVip()
                        ? "续费${entity.title}"
                        : "开通${entity.title}";
                    params.goodsDes = des;
                    params.comboId = int.parse(entity.id);
                    params.goodsPrice = double.parse(entity.discountMoney);
                    params.orderType = AppConstant.PAY_ORDER_MEMBER;
                    LRouter.navigatorCtx(context).push(Routes.paymentPage,
                        arguments: PaymentPageArguments(payParams: params));
                  },
                  child: Text("立即${profileInfo.userInfo.isVip() ? "续费" : "开通"}",
                      style: TextStyle(
                          color: ThemeColors.colorWhite,
                          fontSize: ScreenAdapter.sp(32))))));
    });
  }

  /// 套餐Cell
  Widget _getSetMealCell(int index) {
    MemberComboEntity entity = _comboDatas[index];

    return GestureDetector(
        onTap: () {
          setState(() {
            selectComboIndex = index;
          });
        },
        child: Stack(
          children: [
            Container(
              width: double.infinity,
              margin: EdgeInsets.only(top: ScreenAdapter.height(20)),
              padding: EdgeInsets.only(
                  top: ScreenAdapter.height(20),
                  bottom: ScreenAdapter.height(20)),
              decoration: BoxDecoration(
                border: new Border.all(
                  color: index == selectComboIndex
                      ? ThemeColors.colorType30
                      : ThemeColors.colorType34,
                  width: 1,
                ),
                borderRadius: BorderRadius.circular(ScreenAdapter.width(14)),
                color: index == selectComboIndex
                    ? ThemeColors.colorType35
                    : ThemeColors.colorWhite,
              ),
              child: Column(
                children: <Widget>[
                  Expanded(
                      child: Text(entity.title,
                          style: TextStyle(
                              fontSize: ScreenAdapter.sp(28),
                              color: ThemeColors.colorType2,
                              fontWeight: FontWeight.w600))),
                  Expanded(
                      child: RichText(
                          text: TextSpan(
                    text: '¥ ',
                    style: TextStyle(
                        fontSize: ScreenAdapter.sp(25),
                        color: ThemeColors.colorType30,
                        fontWeight: FontWeight.bold),
                    children: <TextSpan>[
                      TextSpan(
                          text: entity.discountMoney,
                          style: TextStyle(
                            fontSize: ScreenAdapter.sp(45),
                            color: ThemeColors.colorType30,
                          ),
                          children: <TextSpan>[
                            TextSpan(
                                text: '  ¥ ' + entity.money,
                                style: TextStyle(
                                  decoration: TextDecoration.lineThrough,
                                  fontSize: ScreenAdapter.sp(24),
                                  color: ThemeColors.colorType31,
                                ))
                          ]),
                    ],
                  ))),
                  // SizedBox(
                  //     height: ScreenAdapter.height(30),
                  //     child: Text(entity.times + "次查看",
                  //         style: TextStyle(
                  //           fontSize: ScreenAdapter.sp(15),
                  //           color: ThemeColors.colorType31,
                  //         ))),

                  Expanded(
                      child: Container(
                    width: ScreenAdapter.width(170),
                    height: ScreenAdapter.height(35),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: index == selectComboIndex
                            ? ThemeColors.colorType30
                            : ThemeColors.colorType33,
                        borderRadius:
                            BorderRadius.circular(ScreenAdapter.width(28))),
                    child: Text(
                      entity.subTitle,
                      style: TextStyle(
                          fontSize: ScreenAdapter.sp(24),
                          color: index == selectComboIndex
                              ? ThemeColors.colorWhite
                              : ThemeColors.colorType32,
                          fontWeight: FontWeight.w600),
                    ),
                  ))
                ],
              ),
            ),
            Positioned(
                child: entity.isDefault == true
                    ? Image.asset(RPath.imgPath + "icon_vip_recommend.png")
                    : SizedBox(),
                width: ScreenAdapter.width(100)),
          ],
        ));
  }

  String _getMyVipDes({UserInfoEntity entity}) {
    if (entity.level > 0 && !entity.vipValid) {
      // 代表用户购买的次数已用完
      return "您的会员已过期，续费可继续查看";
    } else if (entity.level > 0 && entity.vipValid) {
      // 代表用户是有效会员
      return "您的会员${entity.expireDate}到期";
    }
    return "开通会员尊享更多特权";
  }

  /// 权益列表cell
  Widget _getPermissionCell(CommonItemModel model) {
    return Container(
      child: Column(
        children: <Widget>[
          Image.asset(
            RPath.imgPath + model.image,
            fit: BoxFit.contain,
            width: ScreenAdapter.width(100),
            height: ScreenAdapter.width(100),
          ),
          SizedBox(height: ScreenAdapter.height(10)),
          Text(model.title,
              style: TextStyle(
                  color: ThemeColors.colorType23,
                  fontSize: ScreenAdapter.sp(28)))
        ],
      ),
    );
  }
}
